package com.tbit.uqbike.service.business.brand.config;

import cn.hutool.core.collection.ListUtil;
import com.tbit.uqbike.constant.BrandRemoteConfigConstant;
import com.tbit.uqbike.constant.SubAccountConstant;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.AccountConfigExt;
import com.tbit.uqbike.object.pojo.BrandRemoteConfig;
import com.tbit.uqbike.object.pojo.vo.AreaVO;
import com.tbit.uqbike.service.business.AccountService;
import com.tbit.uqbike.service.business.brand.ctx.ValidateContextHolder;
import com.tbit.uqbike.webmanager.business.machinegroup.dao.core.MachineGroupDao;
import com.tbit.uqbike.webmanager.business.machinegroup.object.vo.MachineGroupVo;
import com.tbit.uqbike.webmanager.business.userdivide.dao.core.UserDivideDao;
import com.tbit.uqbike.webmanager.dao.core.AccountConfigExtDao;
import com.tbit.uqbike.webmanager.dao.core.BrandRemoteConfigDao;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 车辆分账开关校验
 *
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2024/7/17
 */
@Component
@RequiredArgsConstructor
public class AdapayCashTypeValidator extends AbstractConfigValidator {
    final BrandRemoteConfigDao configDao;
    final MachineGroupDao machineGroupDao;
    final UserDivideDao userDivideDao;
    final AccountService accountService;
    final AccountConfigExtDao accountConfigExtDao;

    @Override
    protected boolean support(BrandRemoteConfig brandRemoteConfig) {
        return BrandRemoteConfigConstant.ADAPAY_MONEY_CASH_TYPE.equals(brandRemoteConfig.getConfigType());
    }

    @Override
    public void doValid(BrandRemoteConfig brandRemoteConfig) {
        String paramKV = brandRemoteConfig.getParamKV();

        int button = Integer.parseInt(paramKV.substring(brandRemoteConfig.getParamKV().indexOf("=") + 1));

        // 开启全额分账时，品牌下区域不能开启车辆分账
        if (button == 1) {
            List<Integer> areaIds = accountService.getAreaByBrandId(brandRemoteConfig.getAccountId())
                    .stream().filter(area -> area.getDelFlag() == 0)
                    .map(AreaVO::getAccountId)
                    .collect(Collectors.toList());

            List<AccountConfigExt> configExts = accountConfigExtDao.getByAccountIdsAndType(areaIds, "machineDivideSwitch");
            if (configExts.stream().anyMatch(configExt -> configExt.getParamValue().equals("1"))) {
                throw new BaseException("品牌下有区域开启了车辆分账，请关闭后再开启全额分账");
            }
        }
    }
}
